import { db } from "src/config/database";

function add(tableName: string, params: any) {
  const columns = Object.keys(params);
  const values = Object.values(params);
  const column_st = columns.join(",");
  const value_st = values.map(() => "?");
  const statement = `INSERT INTO ${tableName} (${column_st}) VALUES (${value_st})`;
  return new Promise((resolve, reject) => {
    db!.run(statement, values, function (err) {
      err ? reject(err) : resolve(this);
    });
  });
}

function remove(tableName: string, id: number | string) {
  const statement = `UPDATE ${tableName} SET del_flag = 0 WHERE id = ?`;
  return new Promise((resolve, reject) => {
    db!.run(statement, [id], function (err) {
      err ? reject(err) : resolve(this);
    });
  });
}

function modify(tableName: string, params: any) {
  const { id, ...rest } = params;
  const columns = Object.keys(rest);
  const values = Object.values(rest);
  const column_st = columns.map((key) => `${key} = ?`).join(",");
  const statement = `UPDATE ${tableName} SET ${column_st} WHERE id = ?`;
  return new Promise((resolve, reject) => {
    db!.run(statement, [...values, id], function (err) {
      err ? reject(err) : resolve(this);
    });
  });
}

function queryOne(tableName: string, params: any, field: string) {
  const values = [params[field]];
  const statement = `SELECT * FROM ${tableName} WHERE ${field} =?`;
  return new Promise((resolve, reject) => {
    db!.get(statement, values, (err, row) => {
      err ? reject(err) : resolve(row);
    });
  });
}

export { add, remove, modify, queryOne };
